import axios from "axios";
import { Loading, Message } from "element-ui";

// axios.get("db.json").then(resp => {
//     console.log(resp.data)
// })
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
});
// request.get("db.json").then(resp => {
//     console.log(resp.data)
// })
// instance.interceptors.request.use(function () {/*...*/});

const LoadUtil = {
  LoadingInstance: null,
  open() {
    if (this.LoadingInstance === null) {
      this.LoadingInstance = Loading.service({
        target: ".main",
        fullscreen: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.8)",
        spinner: "el-icon-loading"
      });
    }
  },
  close() {
    if (this.LoadingInstance !== null) {
      this.LoadingInstance.close();
    }
    this.LoadingInstance = null;
  }
};

request.interceptors.request.use(
  config => {
    LoadUtil.open();
    return config;
  },
  error => {
    LoadUtil.close();
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  resp => {
    LoadUtil.close();
    const respData = resp.data;
    if (!respData.flag) {
      Message({
        message: respData.message,
        type: "warning",
        duration: 5000
      });
    }
    return resp;
  },
  error => {
    LoadUtil.close();
    Message({
      message: error,
      type: "error",
      duration: 5000
    });
    return Promise.reject(error);
  }
);

export default request;
